import PageHeaderNew from '@/components/PageHeaderNew/index.vue';
import TableTurn from '@/components/TableTurn/index.vue';
import ContentCard from '@/components/ContentCard/index.vue';
import ConditionBox from '@/components/ConditionBox.vue';
import IconFont from '@/components/IconFont/index.vue';
import styles from './JobLevel.module.less';
import {
  getJobLevelList,
  delJobLevelList
} from '@/apis/management/organization/baseSetting/PositionSystem/index';
import Modals from './Modals';
import { Message, Modal } from '@arco-design/web-vue';
interface from {
  name?: string;
  remark?: string;
  id?: number;
  levelUp?: number;
  levelDown?: number;
}
function timestampToTime(timestamp: string) {
  const timeNum = +new Date(timestamp);
  const date = new Date(timeNum); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  const Y = date.getFullYear() + '-';
  const M =
    (date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1) + '-';
  const D = date.getDate() + ' ';
  const h = date.getHours() + ':';
  const m = date.getMinutes() + ':';
  const s = date.getSeconds();
  return Y + M + D + h + m + s;
}
export default defineComponent({
  setup() {
    const tableTurn = ref<any>(null);
    const args = {
      rowSelection: {
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false
      }
    };
    /* 储存选择的数据 */
    const selectedList = computed(() => tableTurn.value.selectedList);
    // 编辑
    const edit = (id: number) => {
      editId.value = id;
      modalVisible.value = true;
    };
    // 开启刷新
    const openRefresh = (e: boolean) => {
      refresh.value = e;
      if (tableTurn.value) {
        tableTurn.value.loadData();
        refresh.value = false;
      }
    };
    // 删除
    const remove = async (id: number) => {
      try {
        if (!id) {
          if (selectedList.value.length === 0) {
            Message.error('请至少选择一项！');
          } else {
            Modal.confirm({
              title: '提示',
              content: '确定要删除选中的数据吗？',
              onOk: async () => {
                try {
                  await delJobLevelList({
                    ids: selectedList.value
                  });
                  tableTurn.value.selectedList = [];
                  tableTurn.value.loadData();
                } catch (error: unknown) {
                  console.log(error);
                }
              }
            });
          }
        } else {
          await delJobLevelList({
            ids: [id]
          });
          tableTurn.value.selectedList = [];
          tableTurn.value.loadData();
        }
      } catch (error: unknown) {
        console.log(error);
      }
    };
    // 模糊查询
    const keyWord = ref();
    const modalVisible = ref(false); // 判断是否显示弹出框
    const isshowModals = (e: boolean) => {
      modalVisible.value = e;
    };
    // 新增弹窗
    const showModals = () => {
      editId.value = 0;
      modalVisible.value = true;
    };
    // 搜索数据
    const searchData = async () => {
      tableTurn.value.loadData({
        pageNumber: 0,
        pageSize: -1
      });
    };
    // 监听键盘回车，按了回车也会查询
    const keyDown = (e: any) => {
      if (e.keyCode === 13) {
        tableTurn.value.loadData({
          pageNumber: 0,
          pageSize: -1
        });
      }
    };

    onMounted(() => {
      // 监听键盘事件
      window.addEventListener('keydown', keyDown);
    });
    // 刷新数据
    const refresh = ref(false);
    // 所有数据
    const allData: from[] = reactive([]);
    const editId = ref(0);
    const editData = computed(() => {
      if (editId.value === 0) return undefined;
      return allData.filter((ele) => ele?.id === editId.value)[0];
    });
    // 初始数据
    const LegalEntityTypeData = async (page: any) => {
      try {
        let res;
        if (keyWord.value) {
          res = await getJobLevelList({
            ...page,
            postLevelName: String(keyWord.value)
          });
        } else {
          res = await getJobLevelList({
            ...page
          });
        }
        allData.length = 0;
        allData.push(...res.content);
        res.content.map((ele: any) => {
          ele.createdAt = timestampToTime(ele.createdAt);
        });
        return Promise.resolve(res);
      } catch (err: unknown) {
        console.log(err);
      }
    };
    return () => (
      <div>
        <ContentCard
          v-slots={{
            header: () => {
              return (
                <PageHeaderNew
                  title={'职务级别'}
                  breadCrumb={['组织', '基础设置', '职务级别']}
                  showBack
                  isShowBtn={true}
                ></PageHeaderNew>
              );
            }
          }}
        >
          <ConditionBox
            margin-bottom={20}
            v-slots={{
              left: () => {
                return (
                  <a-input-search
                    v-model={keyWord.value}
                    class={styles.input}
                    placeholder="请输入级别名称"
                    onSearch={searchData}
                    search-button
                  />
                );
              },
              right: () => {
                return (
                  <>
                    <a-button onClick={showModals} type="primary">
                      新增级别
                    </a-button>
                    <a-button
                      onClick={() => remove(null)}
                      type="outline"
                      status="danger"
                    >
                      批量删除
                    </a-button>
                  </>
                );
              }
            }}
          ></ConditionBox>
          <TableTurn
            ref={tableTurn}
            args={args}
            tableData={LegalEntityTypeData}
            v-slots={{
              default: () => (
                <>
                  <a-table-column
                    align="center"
                    width={80}
                    v-slots={{
                      title: () => '序号',
                      cell: (props: Record<'rowIndex', number>) =>
                        props.rowIndex + 1
                    }}
                  ></a-table-column>
                  <a-table-column
                    title="职务级别名称"
                    data-index="postLevelName"
                    align="center"
                  ></a-table-column>
                  <a-table-column
                    title="职务级别编号"
                    data-index="postLevelNum"
                    align="center"
                  ></a-table-column>

                  <a-table-column
                    title="备注说明"
                    data-index="remark"
                    align="center"
                  ></a-table-column>
                  {/* <a-table-column
                    title="创建人"
                    data-index="userName"
                    align="center"
                  ></a-table-column>
                  <a-table-column
                    width={200}
                    title="创建时间"
                    data-index="createdAt"
                    align="center"
                  ></a-table-column> */}
                  <a-table-column
                    title="启用状态"
                    data-index="status"
                    align="center"
                    v-slots={{
                      cell: ({ record }: Record<'record', any>) => {
                        return (
                          <a-tag
                            class={styles.enable}
                            color={
                              record.status === 1
                                ? `rgb(var(--green-1))`
                                : 'rgb(var(--danger-1))'
                            }
                            style={{
                              color:
                                record.status === 1
                                  ? `rgb(var(--green-6))`
                                  : 'rgb(var(--danger-6))',
                              '--enable':
                                record.status === 1
                                  ? `rgb(var(--green-6))`
                                  : 'rgb(var(--danger-6))'
                            }}
                          >
                            {record.status === 1 ? '启用' : '停用'}
                          </a-tag>
                        );
                      }
                    }}
                  ></a-table-column>
                  <a-table-column
                    title="操作"
                    align="center"
                    v-slots={{
                      cell: (props: Record<'record', any>) => (
                        <a-space size={0}>
                          <a-tooltip content="编辑">
                            <IconFont
                              type="icon-edit"
                              size={26}
                              style={{
                                cursor: 'pointer'
                              }}
                              onClick={() => edit(props.record.id)}
                            />
                          </a-tooltip>
                          <a-tooltip content="删除" position="left">
                            <a-popconfirm
                              content="是否确认删除该条数据?"
                              position='left'
                              onOk={() => remove(props.record.id)}
                            >
                              <IconFont
                                type="icon-delete"
                                size={26}
                                style={{
                                  cursor: 'pointer'
                                }}
                              />
                            </a-popconfirm>
                          </a-tooltip>
                        </a-space>
                      )
                    }}
                  ></a-table-column>
                </>
              )
            }}
          ></TableTurn>
        </ContentCard>
        {/* <div>表单组件</div> */}
        <Modals
          refresh={refresh.value}
          visible={modalVisible.value}
          oldData={editData.value}
          onChangeVisible={isshowModals}
          onOpenRefresh={openRefresh}
        />
      </div>
    );
  }
});
